class MyURL {
    constructor(url) {
        this._parseUrl(url);
    }

    _parseUrl(url) {
        const urlPattern = /^(https?):\/\/([^:/?#]+)(?::(\d+))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/;
        const match = url.match(urlPattern);

        if (match) {
            this.protocol = match[1] || '';
            this.hostname = match[2] || '';
            this.port = match[3] || '';
            this.pathname = match[4] || '';
            this.search = match[5] || '';
            this.hash = match[6] || '';
        } else {
            throw new Error('Invalid URL');
        }
    }

    // 获取查询参数对象
    get searchParams() {
        return this._parseQueryString(this.search);
    }

    // 设置查询字符串
    set searchParams(params) {
        this.search = '?' + this._stringifyQueryString(params);
    }

    _parseQueryString(query) {
        if (!query) return {};
        return query.slice(1).split('&').reduce((params, param) => {
            const [key, value] = param.split('=');
            params[decodeURIComponent(key)] = decodeURIComponent(value || '');
            return params;
        }, {});
    }

    _stringifyQueryString(params) {
        return Object.keys(params)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
            .join('&');
    }

    // 返回完整的 URL 字符串
    toString() {
        return `${this.protocol}://${this.hostname}${this.port ? `:${this.port}` : ''}${this.pathname}${this.search}${this.hash}`;
    }
}

export default MyURL;
// // 示例用法
// const myUrl = new MyURL('https://example.com:8080/pathname?search=test&category=1#hash');

// // 访问各个部分
// console.log(myUrl.protocol); // https
// console.log(myUrl.hostname); // example.com
// console.log(myUrl.port); // 8080
// console.log(myUrl.pathname); // /pathname
// console.log(myUrl.search); // ?search=test&category=1
// console.log(myUrl.hash); // #hash

// // 获取查询参数
// console.log(myUrl.searchParams); // { search: 'test', category: '1' }

// // 设置查询参数
// myUrl.searchParams = { search: 'updated', category: '2' };
// console.log(myUrl.toString()); // https://example.com:8080/pathname?search=updated&category=2#hash
